<template>
  <a-upload-dragger
    v-if="canEdit"
    v-model:fileList="fileList"
    name="file"
    :multiple="true"
    :action="`${baseURL}/kc/uploadAttach`"
    :data="{ relaId: props.relaId, classify: props.classify }"
    @change="handleChange"
    @drop="handleDrop"
    :showUploadList="false"
  >
    <p class="ant-upload-drag-icon">
      <inbox-outlined></inbox-outlined>
    </p>
    <p class="ant-upload-text">Click or drag file to this area to upload</p>
    <p class="ant-upload-hint">
      Support for a single or bulk upload. Strictly prohibit from uploading
      company data or other band files
    </p>
  </a-upload-dragger>

  <a-tag v-for="attach in attachList" :key="attach.id" color="blue">
    <PaperClipOutlined
      @click="downloadAttach(attach.id, attach.fileName + '.' + attach.suffix)"
      style="cursor: pointer"
    />
    {{ attach.fileName }}

    <a-popconfirm
      title="Are you sure delete this attach?"
      ok-text="Yes"
      cancel-text="No"
      @confirm="deleteAttach(attach.id)"
    >
      <CloseOutlined style="cursor: pointer" v-if="canEdit" />
    </a-popconfirm>

    <CloudDownloadOutlined
      @click="downloadAttach(attach.id, attach.fileName + '.' + attach.suffix)"
      style="cursor: pointer"
    />
  </a-tag>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import {
  InboxOutlined,
  PaperClipOutlined,
  CloseOutlined,
  CloudDownloadOutlined,
} from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import KcHooks from "@/hooks/KcHooks.js";
import { messageApi, contextHolder } from "@/utils/MessageUtils.js";
const cfg = import.meta.env;
const baseURL = cfg.VITE_UPLOAD_BASE_URL;
const props = defineProps({
  relaId: {
    type: String,
    default: "",
  },
  classify: {
    type: String,
    default: "NORMAL",
  },
  canEdit: {
    type: Boolean,
    default: true,
  },
});

const fileList = ref([]);
const handleChange = (info) => {
  const status = info.file.status;
  if (status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (status === "done") {
    message.success(`${info.file.name} file uploaded successfully.`);
    loadPageData();
  } else if (status === "error") {
    message.error(`${info.file.name} file upload failed.`);
  }
};
function handleDrop(e) {
  console.log(e);
}

onMounted(async () => {
  loadPageData();
});
watch(
  () => props.articleId,
  async (v) => {
    loadPageData();
  }
);

const attachList = ref([]);
function loadPageData() {
  if (props.relaId) {
    KcHooks.queryAttachList(props.relaId, "NORMAL").then((res) => {
      attachList.value = res.result;
    });
  }
}

function deleteAttach(attachId) {
  KcHooks.deleteAttach(attachId).then((res) => {
    loadPageData();

    messageApi.success("Delete Successfully");
    loadPageData();
  });
}

async function downloadAttach(attachId, fileName) {
  await KcHooks.downloadAttach(attachId, fileName);
}
</script>

<style>
</style>